<template>
  <el-row>
    <div style="padding-top: 10px;padding-bottom: 10px;width: 300px">
      <el-input placeholder="请输入活动名称" v-model="selectDrawName" class="input-with-select">
        <template #append>
          <el-button icon="el-icon-search" @click="list()"></el-button>
        </template>
      </el-input>

    </div>
    <el-button style="margin-top: 10px;margin-left: 10px;width: 100px;height: 40px" @click="this.dialogFormVisible = true">
      添加活动
    </el-button>
  </el-row>

  <el-table :data="tableData"
            stripe
            border
            style="width: 100%">
<!--    <el-table-column prop="id" label="ID" width="70" sortable></el-table-column>-->
    <el-table-column prop="title" label="活动名" show-overflow-tooltip></el-table-column>
    <el-table-column prop="remark" label="描述" show-overflow-tooltip></el-table-column>
    <el-table-column prop="releaseTime" label="发布时间" width="170" sortable></el-table-column>

    <el-table-column prop="drawScope" label="参与部门范围" width="130" show-overflow-tooltip>
      <template #default="scope">
        <el-dropdown>
          <el-button type="small">
            查看部门<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="name in scope.row.drawScope">{{ name.name }}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>

    </el-table-column>
    <el-table-column prop="prizeList" label="奖项" width="150" show-overflow-tooltip>
      <template #default="scope">
        <el-dropdown>
          <el-button type="small">
            查看奖项信息<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="name in scope.row.prizeList">奖项名：{{
                  name.title
                }}，奖品：{{ name.prizeName }}，中奖人数：{{ name.drawNum }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </el-table-column>
    <el-table-column label="活动状态" width="100">
      <template #default="scope">
        <el-tag type="danger" v-if="scope.row.state==1">正在进行</el-tag>
        <el-tag type="info" v-else>已经结束</el-tag>
      </template>
    </el-table-column>

    <el-table-column label="操作" width="300">
      <template #default="scope">
        <el-button v-if="scope.row.state==1" disabled plain size="mini"  style="margin-right:5px;">下载中奖情况
        </el-button>
        <el-button v-else plain size="mini" @click="handExport(scope.row.id)" style="margin-right:5px;">下载中奖情况
        </el-button>
        <el-button type="primary" v-if="scope.row.state==1" plain size="mini" @click="handleEditPrzie(scope.row.id)" style="margin-right:5px;">编辑
        </el-button>
        <el-button type="primary" v-else disabled plain size="mini"  style="margin-right:5px;">编辑
        </el-button>
        <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row.id)">
          <template #reference>
            <el-button size="mini" type="danger">删除</el-button>
          </template>
        </el-popconfirm>


      </template>
    </el-table-column>
  </el-table>

  <!-- 对话框-->
  <el-dialog
             v-model="dialogFormVisible"
             style="width: 500px"
             @close="handleClose"
  >
    <el-form
        ref="form"
        :model="prizeForm"
        label-width="80px"
    >
      <el-form-item label="活动名称"  >
        <el-input v-model="prizeForm.title"></el-input>
      </el-form-item>
      <el-form-item label="参与范围">
        <el-checkbox-group  v-model="prizeForm.drawScope">
          <el-checkbox  v-for="(department,i) in departmentList" :label="department.id" :key="i" @change="check">
            {{ department.name }}
          </el-checkbox>
        </el-checkbox-group>
        <el-alert
            title="若全不选择则默认全体部门"
            :closable="false"
            type="info"
            style="line-height: 12px;"
        ></el-alert>
      </el-form-item>
      <el-form-item label="活动描述" >
        <el-input type="textarea" v-model="prizeForm.remark"></el-input>
      </el-form-item>
    </el-form>
    <el-form
        ref="prizeForm"
        :inline="true"
        :model="prizeForm"
        label-width="80px"
    >
      <!-- 动态增加项目 -->
      <el-form-item
          v-for="(prize, Index) in prizeForm.prizeList"
          label="奖项名">
        <el-input v-model="prize.title" palceholder="请输入奖项名" style="width: 20%" ></el-input>

        <span style="margin-left: 35px;margin-right: 15px">奖品名</span>
        <el-input v-model="prize.prizeName" palceholder="请输入奖品名" style="width: 20%" ></el-input>
        <span style="margin-left: 15px;margin-right: 10px">中奖人数</span>
        <el-input-number size="small" v-model="prize.drawNum" :min="1"></el-input-number>
        <el-button v-if="Index!=0" type="danger" icon="el-icon-delete" circle @click.prevent="removePrize(prize)"
                   style="margin-left: 20px"></el-button>
      </el-form-item>

    </el-form>


    <template #footer>
              <span class="dialog-footer">
                <el-button type="success" plain @click="addPrize">新增奖项</el-button>
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
              </span>
    </template>
  </el-dialog>

  <div style="float: right;margin-top: 22px;">
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    >
    </el-pagination>

  </div>
</template>

<script>
export default {
  name: "active",
  data() {
    return {
      departmentList: [
        {
          id: null,
          name: '',
          remark: ''
        }
      ],
      prizeForm: {
        id: null,
        title: '',
        remark: '',
        releaseTime: "",
        state: null,
        drawScope: [],
        prizeList: [
          {
            id: null,
            title: "",
            drawNum: '',
            drawId: null,
            prizeName: ""
          }
        ]
      },

      selectDrawName: null,
      size: '',
      total: '',
      current: '',
      dialogFormVisible: false,

      tableData: [
        {
          id: null,
          title: '',
          remark: '',
          releaseTime: "",
          state: null,
          drawScope: [],
          prizeList: [
            {
              id: null,
              title: "",
              drawNum: '',
              drawId: null,
              prizeName: ""
            }
          ]
        }
      ]
    }
  },
  created() {
    this.list(this.selectDrawName)
  },
  methods: {
    check(val){
      console.log(this.prizeForm.drawScope)
    },

    list() {
      this.$axios.get("/draw/list",{
        params: {
          drawName: this.selectDrawName,
          current: this.current,
          size: this.size
        }
      }).then(res => {
        this.size = res.data.data.size
        this.total = res.data.data.total
        this.current = res.data.data.current

        this.tableData = res.data.data.records
        console.log(res)
      })
      this.$axios.get("/department/listAll").then(res => {
        this.departmentList = res.data.data
      })
    },
    submitForm() {
      let drawScopeObj = []
      if (this.prizeForm.drawScope.length == 0){
        this.departmentList.forEach(ds => {
          drawScopeObj.push({"id":ds.id})
        })
        this.prizeForm.drawScope = drawScopeObj
      }else{
        this.prizeForm.drawScope.forEach(ds => {
          drawScopeObj.push({"id":ds})
        })
        this.prizeForm.drawScope = drawScopeObj
      }

      this.$axios.post("/draw/" + (this.prizeForm.id?'update':'save'),this.prizeForm).then(res => {
        this.list(this.selectDrawName)
        this.$message({
          type: 'success',
          message: res.data.msg
        })
      })
      this.handleClose()
    },
    handleDelete(id) {
      console.log(id)
      this.$axios.post("/draw/delete/"+id).then(res => {
          this.$message({
            type: "success",
            message: "删除成功"
        })

        this.list()  // 删除之后重新加载表格的数据
      })
    },
    //这里是分页
    handleSizeChange(val) {
      this.size = val
      this.list()
    },
    handleCurrentChange(val) {
      this.current = val
      this.list()
    },

    removePrize(item) {
      var index = this.prizeForm.prizeList.indexOf(item)
      if (index !== -1) {
        this.prizeForm.prizeList.splice(index, 1)
      }
    },
    addPrize() {
      this.prizeForm.prizeList.push({
        title: '',
        prizeName: '',
        drawNum: null
      })
      console.log(this.prizeList)
    },
    handleClose() {
      this.$refs['prizeForm'].resetFields()
      this.prizeForm = {
        id: '',
        title: '',
        remark: '',
        releaseTime: "",
        state: '',
        drawScope: [],
        prizeList: [
          {
            id: '',
            title: "",
            drawNum: '',
            drawId: '',
            prizeName: ""
          }
        ]
      };
      this.dialogFormVisible = false
    },
    handleEditPrzie(id) {
      this.$axios.get("/draw/info/" + id).then(res => {
        this.dialogFormVisible = true
        this.prizeForm = res.data.data
        let dsArr = []
        this.prizeForm.drawScope.forEach(ds => {
          dsArr.push(ds.id)
        })
        this.prizeForm.drawScope = dsArr
      })

    },
    // excel文件导出
    handExport(id){

      this.$axios.get("/draw/exportLuckUser/"+id,{responseType:"blob"}).then(res => {
        // 获取后端自定义excel表名称
        const fileName = decodeURI(res.headers["content-disposition"].split("=")[1])
        const blob = new Blob([res.data],{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const linkNode = document.createElement('a');
        linkNode.download = fileName; //a标签的download属性规定下载文件的名称
        linkNode.style.display = 'none';
        linkNode.href = URL.createObjectURL(blob); //生成一个Blob URL
        document.body.appendChild(linkNode);
        linkNode.click();  //模拟在按钮上的一次鼠标单击
        URL.revokeObjectURL(linkNode.href); // 释放URL 对象
        document.body.removeChild(linkNode);
      })
    }

  }
}
</script>

<style scoped>

</style>
